package com.herench.bunch.exam.convert;

import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.message.DSR_Q01;
import ca.uhn.hl7v2.model.v24.message.QRY_Q01;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.QRD;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luoxiaoming on 18-10-16 上午10:30
 * @email luoxiaoming@herench.com
 */
public class ExamStatusConvert extends AbstractMessageConvert {

    @Override
    public Map<String,Object> doToMessage(RequestMessage requestMessage) throws Exception {
        Map<String,Object> params = new HashMap<>();
        QRY_Q01 hl7Message = (QRY_Q01) requestMessage.getHl7Message();
        QRD qrd = hl7Message.getQRD();
        CE[] ces = qrd.getQrd9_WhatSubjectFilter();
        for (CE ce : ces) {
            String value = ce.getText().getValue();
            params.put(ce.getCe1_Identifier().getValue(),value!=null?value:"");
        }
//        logger.info(requestMessage.getMsgCode() + " map to string = "+ params);
        return params;
    }

    @Override
    public Message fromMessage(Object message) throws Exception {
        Assert.notNull(message, "message 为空.");
        Map<String, Object> res = (Map<String, Object>) message;
        DSR_Q01 dsr = new DSR_Q01();
        dsr.initQuickstart("DSR_Q01", "Q01", "A");
        MSH msh = dsr.getMSH();
        initResponseMessageMSH(msh);
        MSA msa = dsr.getMSA();
        String ret = (String) res.get("ret");
        if ("0".equals(ret)){
            msa.getErrorCondition().getCe1_Identifier().setValue("0");
            msa.getErrorCondition().getCe2_Text().setValue("操作成功,调用HIS接口返回:ret:"+ret);
        }else {
            msa.getErrorCondition().getCe1_Identifier().setValue("-1");
            msa.getErrorCondition().getCe2_Text().setValue("操作失败,调用HIS接口返回:ret:"+ret);
        }
        return dsr;
    }

    @Override
    public Message generatorReqMessage() throws Exception {
        QRY_Q01 qry = new QRY_Q01();
        qry.initQuickstart("QRY_Q01", "Q01", "A");
        MSH msh = qry.getMSH();
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("300040");
        msh.getMsh11_ProcessingID().getPt2_ProcessingMode().setValue(IdGenerator.getUUID());
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("PACS");
        msh.getMsh7_DateTimeOfMessage().getTs1_TimeOfAnEvent().setValue(new Date());
        msh.getMsh10_MessageControlID().setValue(IdGenerator.getUUID());
        QRD qrd = qry.getQRD();
        addQrd(qrd, "testNo", "M100610000001E");
        addQrd(qrd, "resultStatus", "2");
        addQrd(qrd, "reporter", "1503");
        addQrd(qrd, "verifiedBy", "1503");
        return qry;
    }
}
